package com.chen.common.utils;

import cn.hutool.Hutool;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.chen.common.result.PageResult;
import com.chen.popj.vo.ProblemListVO;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.ArrayList;
import java.util.List;


public class ElasticSearchUtil {

    public static PageResult<ProblemListVO> handleResponse(SearchResponse searchResponse) {
        PageResult<ProblemListVO> pageResult = new PageResult<>();
        SearchHits searchHits = searchResponse.getHits();
        pageResult.setTotal(searchHits.getTotalHits().value);
        SearchHit[] hitsHits = searchHits.getHits();
        List<ProblemListVO> problemListVOList = new ArrayList<>();
        for (SearchHit hitsHit : hitsHits) {
            String source = hitsHit.getSourceAsString();
            ProblemListVO problemListVO = JSONUtil.toBean(source, ProblemListVO.class);
            if (!ObjectUtil.isEmpty(problemListVO)) {
                problemListVOList.add(problemListVO);
            }
        }
        pageResult.setRecords(problemListVOList);
        return pageResult;
    }

}
